import store from '@/store'
// import Vue from 'vue'
// import { Message } from 'element-ui'
// Vue.component(Message.name, Message)

function getWindowClientHeight(){
    let winHeight = 0;
    if (window.innerHeight)
        winHeight = window.innerHeight;
    else if ((document.body) && (document.body.clientHeight))
        winHeight = document.body.clientHeight;
    return winHeight;
}

function getWindowClientWidth(){
    let winWidth = 0;
    if(window.innerHeight)
        winWidth = window.innerWidth;
    else if((document.body) && (document.body.clientWidth))
        winWidth = document.body.clientWidth;
    return winWidth;
}
  
export function getClientHeight(){
    return getWindowClientHeight();
}

export function getTableHeight(){
    return getWindowClientHeight()-220;
}

export function getClientWidth(){
    return getWindowClientWidth();
}

//权限判断
export function hasPermission(permission){
	var permissions = store.state.user.permissions;
    if (permissions && permissions.indexOf(permission) > -1) {
        return true;
    } else {
        return false;
    }
}

/**
 * 获取uuid
 */
export function getUUID () {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
        return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
    })
}

/**
 * 是否有权限
 * @param {*} key
 */
export function isAuth (key) {
    return JSON.parse(sessionStorage.getItem('permissions') || '[]').indexOf(key) !== -1 || false
}

/**
 * base64加密
 * 使用:
 * import * as Tool from '@/utils/tool'
 * Tool.Base64.encode('xxx');
 */
export const Base64 = { _keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9+/=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/rn/g,"n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}}

//ajax错误处理
export const catchError = function(error) {
    let _this = this;
    if (error.response) {
      switch (error.response.status) {
        case 400:
          _this.$message({
            message: error.response.data.msg || '请求参数异常',
            type: 'error'
          });
          break;
        case 401:
        //   sessionStorage.removeItem('user');
          _this.$message({
            message: error.response.data.msg || '密码错误或账号不存在！',
            type: 'warning',
            onClose: function(){
              location.reload();
            }
          });
          break;
        case 403:
          _this.$message({
            message: error.response.data.msg || '无访问权限，请联系企业管理员',
            type: 'warning'
          });
          break;
        default:
          _this.$message({
            message: error.response.data.msg || '服务端异常，请联系技术支持',
            type: 'error'
          });
      }
    }
    return Promise.reject(error);
}


//比较2个对象是否相同
// var obj1 = {id:1,name:"张三"}
// var obj2 = {id:2,name:"李四"}
// var obj3 = {id:1,name:"张三",age:25}
// var obj4 = {id:1,name:"张三"}
// console.log(isObjEqual(obj1,obj2));//false
// console.log(isObjEqual(obj1,obj3));//false
// console.log(isObjEqual(obj1,obj4));//true
export function isObjEqual(o1,o2){
  if(!o2||!o1){
    return false;
  }
  delete o1.__ob__;
  delete o2.__ob__;
  // delete o1.subItems;
  // delete o2.subItems;
  var props1 = Object.getOwnPropertyNames(o1);
  var props2 = Object.getOwnPropertyNames(o2);
  for (var i = 0,max = props1.length; i < max; i++) {
    var propName = props1[i];
    if (propName!='subItems'&&o2[propName]&&o1[propName] !== o2[propName]) {
      return false;
    }
  }
  return true;
}

export function copy(obj){
  var newobj = {};
  for ( var attr in obj) {
    newobj[attr] = obj[attr];
  }
  return newobj;
}

export function copyArr(arr) {
  let res = []
  for (let i = 0; i < arr.length; i++) {
    if(arr[i] instanceof Array) {
      var newArr = [];
      var subArr = arr[i];
      for (var item in subArr) {
        newArr.push(subArr[item]);
      }
      res.push(newArr)
    }else{
      res.push(arr[i])
    }

  }
  return res
}

/**
 * 树形数据转换
 * @param {*} data
 * @param {*} id
 * @param {*} pid
 */
export function treeDataTranslate (data, id = 'id', pid = 'parentId') {
    var res = []
    var temp = {}
    for (var i = 0; i < data.length; i++) {
        temp[data[i][id]] = data[i]
    }
    for (var k = 0; k < data.length; k++) {
        if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
        if (!temp[data[k][pid]]['children']) {
            temp[data[k][pid]]['children'] = []
        }
        if (!temp[data[k][pid]]['_level']) {
            temp[data[k][pid]]['_level'] = 1
        }
        data[k]['_level'] = temp[data[k][pid]]._level + 1
        temp[data[k][pid]]['children'].push(data[k])
        } else {
        res.push(data[k])
        }
    }
    return res
}

export function formatDate(time,cFormat) {
  if (arguments.length === 0) {
      return null
  }
  if(!time){
      return '';
  }
  
  let fmt = cFormat || 'yyyy-MM-dd HH:mm:ss';

  let date;
  if (typeof time === 'object') {
      date = time;
  } else if(typeof time === 'string'){
      date = new Date(time);
  }else{
      date = new Date(parseInt(time));
  }

  var o = {
      "M+" : date.getMonth()+1, //月份
      "d+" : date.getDate(), //日
      "h+" : date.getHours()%12 == 0 ? 12 : date.getHours()%12, //小时
      "H+" : date.getHours(), //小时
      "m+" : date.getMinutes(), //分
      "s+" : date.getSeconds(), //秒
      "q+" : Math.floor(( date.getMonth()+3)/3), //季度
      "S" : date.getMilliseconds() //毫秒
  };
  var week = {
      "0" : "\u65e5",
      "1" : "\u4e00",
      "2" : "\u4e8c",
      "3" : "\u4e09",
      "4" : "\u56db",
      "5" : "\u4e94",
      "6" : "\u516d"
  };
  if(/(y+)/.test(fmt)){
      fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"" ).substr(4 - RegExp.$1.length));
  }
  if(/(E+)/.test(fmt)){
      fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "\u661f\u671f" : "\u5468" ) : "")+week[date .getDay()+"" ]);
  }
  for(var k in o){
      if(new RegExp( "("+ k + ")").test(fmt)){
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00" + o[k]).substr((""+ o[k]).length)));
      }
  }
  return fmt;
}
